<template>
  <div class="form-preview">
    <div class="form-header">
      <div class="header-left">
        <h2>{{ form.name }}</h2>
        <el-button type="primary" @click="showDataManagement = true">
          <el-icon><Document /></el-icon>
          数据管理
        </el-button>
      </div>
    </div>
    
    <div class="form-content">
      <el-form
        ref="formRef"
        :model="formData"
        label-position="top"
        @submit.prevent="handleSubmit"
        class="preview-form"
      >
        <!-- 动态渲染表单组件 -->
        <template v-for="component in form.definition.components" :key="component.id">
          <template v-if="component.type === 'row'">
            <div class="row-container" :style="getComponentStyle(component)">
              <div 
                v-for="(rowItem, rowIndex) in component.props.items" 
                :key="rowIndex"
                class="row-item"
              >
                <el-form-item 
                  :label="rowItem.label" 
                  :prop="rowItem.field"
                  :class="[
                    rowItem.props.labelPosition === 'top' ? 'label-top' : 'label-left'
                  ]"
                >
                  <component
                    :is="rowItem.component"
                    v-model="formData[rowItem.field]"
                    v-bind="rowItem.props"
                    :placeholder="rowItem.props.placeholder"
                    :style="getComponentStyle(rowItem)"
                  />
                </el-form-item>
              </div>
            </div>
          </template>
          <template v-else-if="component.type === 'grid'">
            <el-row
              :gutter="component.props.gutter"
              :justify="component.props.justify"
              :align="component.props.align"
              :type="component.props.type"
              class="grid-container"
              :style="getComponentStyle(component)"
            >
              <el-col
                v-for="(col, colIndex) in component.props.children"
                :key="colIndex"
                :span="24 / component.props.cols"
                class="grid-col"
              >
                <div class="grid-col-content">
                  <template v-if="col.items && col.items.length">
                    <el-form-item
                      v-for="(subItem, subIndex) in col.items"
                      :key="subIndex"
                      :label="subItem.label"
                      :prop="subItem.field"
                      :class="[
                        subItem.props.labelPosition === 'top' ? 'label-top' : 'label-left'
                      ]"
                    >
                      <component
                        :is="subItem.component"
                        v-model="formData[subItem.field]"
                        v-bind="subItem.props"
                        :placeholder="subItem.props.placeholder"
                        :style="getComponentStyle(subItem)"
                      />
                    </el-form-item>
                  </template>
                </div>
              </el-col>
            </el-row>
          </template>
          <el-form-item
            v-else
            :label="component.label"
            :prop="component.field"
            :rules="component.rules"
            :class="[
              component.props.labelPosition === 'top' ? 'label-top' : 'label-left',
              component.type === 'divider' ? 'divider-wrapper' : ''
            ]"
            :style="getFormItemStyle(component)"
          >
            <!-- 文本输入 -->
            <el-input
              v-if="component.type === 'input'"
              v-model="formData[component.field]"
              :placeholder="component.placeholder"
              :style="getComponentStyle(component)"
              v-bind="component.props"
            />
            
            <!-- 数字输入 -->
            <el-input-number
              v-else-if="component.type === 'number'"
              v-model="formData[component.field]"
              :min="component.props.min"
              :max="component.props.max"
              :step="component.props.step"
              :style="getComponentStyle(component)"
              v-bind="component.props"
            />
            
            <!-- 选择器 -->
            <el-select
              v-else-if="component.type === 'select'"
              v-model="formData[component.field]"
              :placeholder="component.placeholder"
              :style="getComponentStyle(component)"
              v-bind="component.props"
            >
              <el-option
                v-for="option in component.props.options"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
            
            <!-- 日期选择器 -->
            <el-date-picker
              v-else-if="component.type === 'date'"
              v-model="formData[component.field]"
              :type="component.props.type || 'date'"
              :placeholder="component.placeholder"
              :style="getComponentStyle(component)"
              v-bind="component.props"
            />
            
            <!-- 文本域 -->
            <el-input
              v-else-if="component.type === 'textarea'"
              v-model="formData[component.field]"
              type="textarea"
              :rows="component.props.rows || 3"
              :placeholder="component.placeholder"
              :style="getComponentStyle(component)"
              v-bind="component.props"
            />
            
            <!-- 分割线 -->
            <el-divider
              v-else-if="component.type === 'divider'"
              :style="getComponentStyle(component)"
            />
            
            <!-- 单选框组 -->
            <el-radio-group
              v-else-if="component.type === 'radio'"
              v-model="formData[component.field]"
              :style="getComponentStyle(component)"
            >
              <el-radio
                v-for="option in component.props.options"
                :key="option.value"
                :label="option.value"
                :style="{
                  fontFamily: component.props.fontFamily,
                  fontSize: component.props.fontSize + 'px',
                  color: component.props.fontColor
                }"
              >
                {{ option.label }}
              </el-radio>
            </el-radio-group>
            
            <!-- 复选框组 -->
            <div v-else-if="component.type === 'checkbox'" 
                 class="checkbox-group-container"
                 :style="getComponentStyle(component)">
              <div v-if="component.props.showCheckAll" class="checkbox-all">
                <el-checkbox
                  v-model="checkAllStates[component.field]"
                  @change="(val) => handleCheckAllChange(val, component)"
                >全选</el-checkbox>
              </div>
              <div class="checkbox-list">
                <el-checkbox
                  v-for="option in component.props.options"
                  :key="option.value"
                  v-model="formData[component.field]"
                  :label="option.value"
                  @change="() => updateCheckAllState(component)"
                >
                  {{ option.label }}
                </el-checkbox>
              </div>
            </div>
          </el-form-item>
        </template>
        
        <div class="form-actions">
          <el-button type="primary" @click="handleSubmit">提交</el-button>
          <el-button @click="handleReset">重置</el-button>
        </div>
      </el-form>
    </div>

    <!-- 数据管理对话框 -->
    <el-dialog
      v-model="showDataManagement"
      title="数据管理"
      width="80%"
      :close-on-click-modal="false"
    >
      <el-table :data="formDataList" style="width: 100%" v-loading="loading">
        <el-table-column prop="submitTime" label="提交时间" width="180" sortable>
          <template #default="scope">
            {{ formatDate(scope.row.submitTime) }}
          </template>
        </el-table-column>
        <template v-for="component in getValidComponents(form.definition.components)" :key="component.id">
          <el-table-column :prop="'data.' + component.field" :label="component.label">
            <template #default="scope">
              <template v-if="component.type === 'checkbox'">
                {{ formatCheckboxValue(scope.row.data[component.field], component) }}
              </template>
              <template v-else-if="component.type === 'date'">
                {{ formatDate(scope.row.data[component.field]) }}
              </template>
              <template v-else>
                {{ scope.row.data[component.field] }}
              </template>
            </template>
          </el-table-column>
        </template>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button type="danger" size="small" @click="handleDeleteData(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import axios from 'axios'

const API_BASE_URL = 'http://localhost:5000/api'

interface FormComponent {
  id: string
  type: string
  field: string
  label: string
  placeholder?: string
  rules?: any[]
  options?: { label: string; value: any }[]
  min?: number
  max?: number
  step?: number
  rows?: number
  dateType?: string
}

interface FormDefinition {
  components: FormComponent[]
  layout: any
  settings: any
}

interface Form {
  id: string
  name: string
  type: string
  definition: FormDefinition
}

const props = defineProps<{
  form: Form
}>()

const formRef = ref<FormInstance>()
const formData = reactive<Record<string, any>>({})
const showDataManagement = ref(false)
const formDataList = ref<any[]>([])
const loading = ref(false)
const checkAllStates = reactive<Record<string, boolean>>({})

// 获取组件样式
const getComponentStyle = (component: any) => {
  const style: any = {
    fontFamily: component.props.fontFamily,
    fontSize: component.props.fontSize + 'px',
    color: component.props.fontColor,
    backgroundColor: component.props.backgroundColor,
    borderStyle: component.props.borderStyle,
    borderColor: component.props.borderColor,
    borderWidth: component.props.borderWidth + 'px',
    borderRadius: component.props.borderRadius + 'px',
    padding: component.props.padding + 'px',
    margin: component.props.margin + 'px'
  }

  // 添加宽度设置
  if (component.props.widthType === 'px') {
    style.width = `${component.props.width}px`
  } else if (component.props.widthType === 'percent') {
    style.width = `${component.props.width}%`
  }

  // 添加高度设置
  if (component.props.heightType === 'px') {
    style.height = `${component.props.height}px`
  }

  return style
}

// 获取表单项样式
const getFormItemStyle = (component: any) => {
  return {
    marginBottom: '22px'
  }
}

// 处理全选变化
const handleCheckAllChange = (val: boolean, component: any) => {
  if (!Array.isArray(formData[component.field])) {
    formData[component.field] = []
  }
  if (val) {
    formData[component.field] = component.props.options.map(opt => opt.value)
  } else {
    formData[component.field] = []
  }
}

// 更新全选状态
const updateCheckAllState = (component: any) => {
  if (!Array.isArray(formData[component.field])) {
    formData[component.field] = []
  }
  checkAllStates[component.field] = 
    component.props.options.length > 0 && 
    formData[component.field].length === component.props.options.length
}

// 初始化表单数据
onMounted(() => {
  // 递归初始化所有组件的数据
  const initComponentData = (components) => {
    components.forEach(component => {
      if (component.type === 'row' && component.props.items) {
        // 初始化行容器中的组件
        initComponentData(component.props.items)
      } else if (component.type === 'grid' && component.props.children) {
        // 初始化栅格布局中的组件
        component.props.children.forEach(col => {
          if (col.items) {
            initComponentData(col.items)
          }
        })
      } else if (component.type === 'checkbox') {
        formData[component.field] = []
        checkAllStates[component.field] = false
      } else {
        formData[component.field] = ''
      }
    })
  }

  // 初始化所有组件数据
  initComponentData(props.form.definition.components)
})

// 加载已提交的表单数据
const loadFormDataList = async () => {
  loading.value = true
  try {
    const response = await axios.get(`${API_BASE_URL}/form/data/${props.form.id}`)
    if (response.data.code === 0) {
      formDataList.value = response.data.data || []
    } else {
      throw new Error(response.data.message || '加载数据失败')
    }
  } catch (error) {
    console.error('加载表单数据错误:', error)
    ElMessage.error('加载数据失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 监听数据管理对话框的显示
watch(showDataManagement, (newVal) => {
  if (newVal) {
    loadFormDataList()
  }
})

// 格式化日期
const formatDate = (date: string | number) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

// 格式化复选框值
const formatCheckboxValue = (value: any[], component: any) => {
  if (!Array.isArray(value)) return ''
  return value
    .map(v => component.options?.find(opt => opt.value === v)?.label || v)
    .join(', ')
}

// 删除表单数据
const handleDeleteData = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除这条数据吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await axios.delete(`${API_BASE_URL}/form/data/${props.form.id}/${row.id}`)
    if (response.data.code === 0) {
      ElMessage.success('删除成功')
      await loadFormDataList()
    } else {
      throw new Error(response.data.message || '删除失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除数据错误:', error)
      ElMessage.error('删除失败，请检查网络连接')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 收集有效的表单数据（只包含有字段名的组件）
    const validFormData = {}
    const collectValidData = (components) => {
      components.forEach(component => {
        if (component.type === 'row' && component.props.items) {
          // 处理行容器中的组件
          collectValidData(component.props.items)
        } else if (component.type === 'grid' && component.props.children) {
          // 处理栅格布局中的组件
          component.props.children.forEach(col => {
            if (col.items) {
              collectValidData(col.items)
            }
          })
        } else if (component.field) {
          // 只收集有字段名的组件数据
          validFormData[component.field] = formData[component.field]
        }
      })
    }

    // 收集所有有效数据
    collectValidData(props.form.definition.components)
    
    // 准备提交数据
    const submitData = {
      formId: props.form.id,
      formName: props.form.name,
      data: validFormData,
      submitTime: new Date().toISOString()
    }
    
    // 提交到后端
    const response = await axios.post(`${API_BASE_URL}/form/data/${props.form.name}`, submitData)
    
    if (response.data.code === 0) {
      ElMessage.success('提交成功')
      handleReset()
    } else {
      throw new Error(response.data.message || '提交失败')
    }
  } catch (error) {
    console.error('提交表单错误:', error)
    ElMessage.error('提交失败，请检查表单数据')
  }
}

// 重置表单
const handleReset = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 添加获取有效组件的方法
const getValidComponents = (components) => {
  const validComponents = []
  
  const collectValidComponents = (items) => {
    items.forEach(component => {
      if (component.type === 'row' && component.props.items) {
        // 处理行容器中的组件
        collectValidComponents(component.props.items)
      } else if (component.type === 'grid' && component.props.children) {
        // 处理栅格布局中的组件
        component.props.children.forEach(col => {
          if (col.items) {
            collectValidComponents(col.items)
          }
        })
      } else if (component.field && component.type !== 'row' && component.type !== 'grid') {
        // 只收集有字段名且不是容器类型的组件
        validComponents.push(component)
      }
    })
  }

  collectValidComponents(components)
  return validComponents
}
</script>

<style scoped>
.form-preview {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.form-header {
  margin-bottom: 24px;
  background-color: #fff;
  padding: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-left h2 {
  color: #303133;
  margin: 0;
}

.form-content {
  flex: 1;
  overflow: auto;
}

.preview-form {
  max-width: 100%;
  margin: 0 auto;
  background-color: #fff;
  padding: 32px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.form-actions {
  padding-top: 5px;
  margin: 0;
  display: flex;
  justify-content: center;
  gap: 12px;
}

/* 修改表单项的基础样式 */
:deep(.el-form-item) {
  margin: 0;  /* 移除默认margin */
  padding: 0 0 5px 0;  /* 使用padding来控制间距 */
  position: relative;  /* 确保定位正确 */
}

:deep(.el-form-item:last-child) {
  padding-bottom: 0;  /* 最后一个元素不需要底部间距 */
}

/* 标签在左侧时的样式 */
:deep(.label-left) {
  display: flex;
  flex-direction: row;
  align-items: flex-start;  /* 改为顶部对齐 */
  min-height: 32px;  /* 保证最小高度 */
  margin: 0;  /* 移除默认margin */
  padding: 0 0 5px 0;  /* 使用padding控制间距 */
}

:deep(.label-left .el-form-item__label) {
  text-align: right;
  padding: 0 12px 0 0;
  width: 100px;
  line-height: 32px;  /* 与输入框对齐 */
  flex-shrink: 0;  /* 防止标签宽度被压缩 */
}

:deep(.label-left .el-form-item__content) {
  flex: 1;
  min-width: 0;  /* 防止内容溢出 */
}

/* 标签在顶部时的样式 */
:deep(.label-top) {
  display: flex;
  flex-direction: column;
  padding: 0 0 5px 0;
  margin: 0;
}

:deep(.label-top .el-form-item__label) {
  text-align: left;
  padding: 0 0 8px 0;
  margin: 0;
  width: 100%;
  line-height: 1.5;
}

/* 容器组件样式调整 */
.row-container {
  display: flex;
  flex-wrap: nowrap;
  gap: 20px;
  align-items: flex-start;
  padding: 16px;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  background-color: #fff;
  margin-bottom: 5px;
}

.row-item {
  flex: 1;
  min-width: 0;
}

.row-item :deep(.el-form-item) {
  margin-bottom: 0;
}

.row-item :deep(.el-form-item__content) {
  width: 100%;
}

.row-item :deep(.el-form-item:last-child) {
  margin-bottom: 0;
}

.row-container:hover {
  border-color: #409EFF;
  box-shadow: 0 0 8px rgba(64, 158, 255, 0.1);
}

.grid-container {
  padding: 16px;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  background-color: #fff;
  margin-bottom: 5px;
}

.grid-col {
  min-height: 50px;
}

.grid-col-content {
  height: 100%;
}

.grid-col-content :deep(.el-form-item) {
  padding-bottom: 5px;
}

.grid-col-content :deep(.el-form-item:last-child) {
  padding-bottom: 0;
}

.grid-col-content :deep(.el-form-item__content) {
  width: 100%;
}

/* 分割线样式调整 */
:deep(.divider-wrapper) {
  padding: 5px 0;
  margin: 0;
}

:deep(.divider-wrapper .el-divider) {
  margin: 0;
}

/* 确保表单项内容对齐 */
:deep(.el-form-item__content) {
  display: flex;
  align-items: center;
  min-height: 32px;  /* 与输入框高度保持一致 */
}

/* 输入框和选择器等组件的统一高度 */
:deep(.el-input__wrapper),
:deep(.el-select),
:deep(.el-date-editor.el-input),
:deep(.el-input-number) {
  height: 32px;
  line-height: 32px;
}

/* 修复复选框组和单选框组的样式 */
.checkbox-group-container,
:deep(.el-radio-group) {
  padding: 4px 0;
}

.checkbox-all {
  margin-bottom: 8px;
  padding-bottom: 8px;
  border-bottom: 1px solid #EBEEF5;
}

.checkbox-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

:deep(.el-checkbox) {
  margin-right: 0;
  margin-left: 0;
  height: 32px;
  display: flex;
  align-items: center;
}

:deep(.el-checkbox__input) {
  pointer-events: auto;
  cursor: pointer;
}

:deep(.el-checkbox__label) {
  pointer-events: auto;
  cursor: pointer;
}

:deep(.el-checkbox.is-disabled) {
  cursor: pointer;
}

:deep(.el-checkbox.is-disabled .el-checkbox__input) {
  cursor: pointer;
  background-color: transparent;
}

:deep(.el-checkbox.is-disabled .el-checkbox__label) {
  cursor: pointer;
  color: #606266;
}

:deep(.el-checkbox__input.is-disabled.is-checked .el-checkbox__inner) {
  background-color: #409EFF;
  border-color: #409EFF;
}

:deep(.el-checkbox__input.is-disabled .el-checkbox__inner) {
  background-color: #fff;
  border-color: #dcdfe6;
  cursor: pointer;
}

/* 数据管理表格样式 */
:deep(.el-table) {
  margin-top: 16px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-select .el-input) {
  width: 100%;
}

:deep(.el-select__tags) {
  width: 100%;
  flex-wrap: wrap;
}
</style> 